<script lang="tsx">
import { computed, defineComponent, type PropType, unref } from 'vue'
import { ElOption, ElSelect } from 'element-plus'
import { get, isArray, isUndefined, omit } from 'lodash-es'
import type { OptionsItem } from '../types/formItem'
import { propTypes } from '@/types/propTypes'
import { useRuleFormItem } from '../common/useFormItem'
import type { Recordable } from '@/types/global'

export default defineComponent({
  name: 'BasicFormSelect',
  props: {
    //当前数参数
    options: {
      type: Array as PropType<OptionsItem[]>,
      default: () => [],
    },
    modelValue: {
      type: [String, Number, Boolean, Array],
      default: '',
    },
    modelName: {
      type: [String, Number, Boolean, Array],
    },
    labelField: propTypes.string.def('label'),
    valueField: propTypes.string.def('value'),
    onChange: {
      type: Function,
      default: () => {},
    },
  },
  emit: ['update:modelValue', 'update:modelName'],
  setup(props, { emit, attrs, slots }) {
    const [state] = useRuleFormItem(props, 'modelValue', 'update:modelValue')
    const getOptions = computed(() => {
      const { labelField, valueField, options } = props
      const optionArr = unref(options).reduce((prev, next: Recordable) => {
        if (next) {
          prev.push({
            ...omit(next, [labelField, valueField]),
            label: get(next, labelField),
            value: get(next, valueField),
          })
        }
        return prev
      }, [] as OptionsItem[])

      return optionArr
    })
    function handleChange(args: any) {
      props.onChange(args)
      if (isUndefined(args)) {
        emit('update:modelName', args)
      } else if (isArray(args)) {
        let name: string[] = []
        if (args.length) {
          args.forEach((ve: Recordable) => {
            let one: OptionsItem[] = unref(getOptions).filter((e: Recordable) => e.value == ve)
            if (one[0] && one[0].label !== undefined) {
              name.push(one[0].label)
            }
          })
        }
        emit('update:modelName', name)
      } else {
        unref(getOptions).forEach((e: Recordable) => {
          if (e.value == args) {
            emit('update:modelName', e.label)
          }
        })
      }
    }
    // console.log("att", slots.header)

    function RenderOption() {
      return getOptions.value.map((e: any, index: number) => {
        return (
          <ElOption
            value={e.value}
            key={index + e.value}
            label={e.label}
            disabled={e.disabled || false}
          />
        )
      })
    }

    return () => {
      return (
        <div>
          <ElSelect {...attrs} v-slots={slots} model-value={state.value} onChange={handleChange}>
            {RenderOption()}
          </ElSelect>
        </div>
      )
    }
  },
})
</script>
